import torch
import torch.nn as nn
import torch.optim as optim
import torchvision
import torchvision.transforms as transforms
from tqdm import tqdm
import torch.nn.functional as F
import matplotlib.pyplot as plt

# 数据预处理
transform = transforms.Compose([
    transforms.ToTensor(),
    transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5)),
])

# 加载 CIFAR-10 数据集
trainset = torchvision.datasets.CIFAR10(root='./data', train=True, download=True, transform=transform)
trainloader = torch.utils.data.DataLoader(trainset, batch_size=64, shuffle=True, num_workers=2)

testset = torchvision.datasets.CIFAR10(root='./data', train=False, download=True, transform=transform)
testloader = torch.utils.data.DataLoader(testset, batch_size=64, shuffle=False, num_workers=2)

# 定义模型
class FuzzyInferenceBlock(nn.Module):
    def __init__(self, output_dim, i_fmap, mu, sigma, n_feature, fRules_sigma):
        super(FuzzyInferenceBlock, self).__init__()
        self.output_dim = output_dim
        self.index = i_fmap

        self.mu = nn.Parameter(torch.tensor(mu, dtype=torch.float32).cuda())  # 移动到GPU
        self.sigma = nn.Parameter(torch.tensor(sigma, dtype=torch.float32).cuda())  # 移动到GPU

        self.n_feature = n_feature
        self.fRules_sigma = fRules_sigma
        self.mu_map = fRules_sigma * self.mu
        self.sigma_map = torch.ones((n_feature, output_dim), dtype=torch.float32).cuda() * self.sigma  # 移动到GPU

    def forward(self, inputs):
        fMap = inputs[:, self.n_feature * self.index:self.n_feature * (self.index + 1)]
        aligned_x = fMap.unsqueeze(-1).expand(-1, -1, self.output_dim)
        aligned_c = self.mu_map
        aligned_s = self.sigma_map
        phi = torch.exp(-torch.sum((aligned_x - aligned_c) ** 2 / (2 * aligned_s ** 2), dim=-2))
        return phi

class FCNN(nn.Module):
    def __init__(self, n_femap=4, stride=2, mu=3.0, sigma=1.2, dropout=True, num_classes=10):
        super(FCNN, self).__init__()
        self.dropout = dropout
        self.conv1 = nn.Conv2d(3, 20, kernel_size=3, stride=3, padding=1)
        self.conv2 = nn.Conv2d(20, 40, kernel_size=3, stride=2, padding=1)
        self.conv3 = nn.Conv2d(40, 40, kernel_size=3, stride=2, padding=1)
        self.conv4 = nn.Conv2d(40, 40, kernel_size=3, stride=2, padding=1)
        self.conv5 = nn.Conv2d(40, n_femap, kernel_size=3, stride=stride, padding=0)

        if self.dropout:
            self.dropout_layer = nn.Dropout(0.2)

        self.n_femap = n_femap
        self.fuzzy_blocks = nn.ModuleList([
            FuzzyInferenceBlock(output_dim=10, i_fmap=i, mu=mu, sigma=sigma, n_feature=n_femap, fRules_sigma=1.0)
            for i in range(n_femap)
        ])
        self.fc = nn.Linear(n_femap * 10, num_classes)

    def forward(self, x):
        x = F.relu(self.conv1(x))
        x = F.max_pool2d(x, kernel_size=3, stride=1, padding=1)

        x = F.relu(self.conv2(x))
        x = F.max_pool2d(x, kernel_size=2, stride=1, padding=1)

        x = F.relu(self.conv4(x))
        x = F.max_pool2d(x, kernel_size=2, stride=1, padding=1)

        x = F.relu(self.conv5(x))
        if self.dropout:
            x = self.dropout_layer(x)

        x = x.view(x.size(0), -1)
        fuzzy_outputs = [self.fuzzy_blocks[i](x) for i in range(self.n_femap)]
        merged = torch.cat(fuzzy_outputs, dim=1)
        out = self.fc(merged)
        return out

# 训练设置
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")  # 检查GPU是否可用
model = FCNN().to(device)  # 移动模型到GPU
criterion = nn.CrossEntropyLoss()
optimizer = optim.Adam(model.parameters(), lr=0.001)
losses = []

# 训练过程
num_epochs = 10  # 可以根据需要调整
for epoch in range(num_epochs):
    model.train()
    running_loss = 0.0
    for inputs, labels in tqdm(trainloader):
        inputs, labels = inputs.to(device), labels.to(device)  # 移动输入和标签到GPU

        optimizer.zero_grad()
        outputs = model(inputs)
        loss = criterion(outputs, labels)
        loss.backward(retain_graph=True)
        optimizer.step()

        running_loss += loss.item()

    print(f"Epoch [{epoch + 1}/{num_epochs}], Loss: {running_loss / len(trainloader):.4f}")
    losses.append(running_loss / len(trainloader))

# 绘制损失图
plt.plot(losses)
plt.xlabel('Epochs')
plt.ylabel('Loss')
plt.title('Training Loss Over Epochs')
plt.show()

# 测试过程
model.eval()
correct = 0
total = 0
with torch.no_grad():
    for inputs, labels in testloader:
        inputs, labels = inputs.to(device), labels.to(device)  # 移动输入和标签到GPU
        outputs = model(inputs)
        _, predicted = torch.max(outputs.data, 1)
        total += labels.size(0)
        correct += (predicted == labels).sum().item()

print(f'Accuracy of the model on the 10000 test images: {100 * correct / total:.2f}%')
